package com.efast.cafe.commponent.crud.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.ObjectUtils;
import com.efast.cafe.commponent.crud.service.ICrudV2Service;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.util.LanguageUtil;
import com.efast.cafe.portal.bean.common.AttachmentFormBean;
import com.efast.cafe.portal.bean.common.DateValidationBean;
import com.efast.cafe.portal.bean.common.DoubleValidationBean;
import com.efast.cafe.portal.bean.common.EntityFieldDetailBean;
import com.efast.cafe.portal.bean.common.EntityFieldInfoBean;
import com.efast.cafe.portal.bean.common.EntityInfoBean;
import com.efast.cafe.portal.bean.common.IntValidationBean;
import com.efast.cafe.portal.bean.common.StringValidationBean;
import com.efast.cafe.portal.entity.base.PortalBaseLov;
import com.efast.cafe.portal.entity.common.PortalAttachmentForm;
import com.efast.cafe.portal.entity.common.PortalMultiEntityBean;
import com.efast.cafe.portal.remote.base.PortalBaseLovService;
import com.efast.cafe.portal.remote.common.EntityInfoQueryService;
import com.efast.cafe.portal.remote.common.PortalAttachmentService;
import com.efast.cafe.util.StringUtil;
import com.efast.cafe.util.date.DateUtils;

import net.sf.json.JSONObject;

@Service
@Transactional
public class CrudV2ServiceImpl implements ICrudV2Service {

	@Autowired
	private EntityInfoQueryService entityInfoQueryService;

	@Autowired 
	private PortalBaseLovService portalBaseLovService ;


	@Autowired
	@Qualifier("jdbcDao")
	private JdbcDao jdbcDao;
	
	@Autowired
	private CrudSqlGenerateUtils crudSqlGenerateUtils;

	@Autowired
	private PortalAttachmentService portalAttachmentService;

	


	protected static final Logger log = LoggerFactory.getLogger(CrudV2ServiceImpl.class);

	@Override
	public Integer crudInsert(String entityName, Map<String, Object> param, AttachmentFormBean attachments) {
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition",entityName);
		}
		List<Object> params= new ArrayList<>() ;  
		String sql = crudSqlGenerateUtils.buildInsertSql(entityInfo.getTableName(), param, entityInfo.getAttrs(),entityInfo.getExtAttrs(), false,params);
		Integer id = jdbcDao.insertBySQLAndGetKey(sql,params);
		if (param.get("generateFormId") != null) {
			portalAttachmentService.saveAttachmentForm(param.get("generateFormId").toString(), attachments!=null?attachments.getAttachments():null);
		}
		return id;
	}

	@Override
	public void crudUpdate(String entityName, Map<String, Object> param, AttachmentFormBean attachments) {
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition",entityName);
		}
		List<Object> params= new ArrayList<>() ;
		String sql = crudSqlGenerateUtils.buildUpdateSql(entityInfo.getTableName(), param, entityInfo.getAttrs(),entityInfo.getExtAttrs(), false, params);
		jdbcDao.executeBySQL(sql,params);
		if (param.get("generateFormId") != null) {
			portalAttachmentService.saveAttachmentForm(param.get("generateFormId").toString(),attachments!=null?attachments.getAttachments():null);
		}
	}

	@Override
	public void crudDelete(String entityName, Map<String, Object> param) {
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition",entityName);
		}
		List<Object> params= new ArrayList<>() ;
		String sql = crudSqlGenerateUtils.buildDeleteSql(entityInfo.getTableName(), param, entityInfo.getAttrs(), params);
		jdbcDao.executeBySQL(sql,params);
	}

	@Override
	public Object crudFindById(String entityName, Map<String, Integer> map) {
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition",entityName);
		}
		List<Object> params= new ArrayList<>() ;
		String sql = crudSqlGenerateUtils.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(),entityInfo.getExtAttrs(), false , params);
		List<Map<String, Object>> data = jdbcDao.queryForListMap(sql,params);
		return data != null && data.size() > 0 ? data.get(0) : null;

	}
	
	
	

	@Override
	public void multiEntityInsert(String entityName, PortalMultiEntityBean portalMultiEntityBean) {
		Long id = null ; 
		EntityInfoBean entityInfo1 = entityInfoQueryService.queryEntityInfo(portalMultiEntityBean.getEntityKey());
		// 获取实体定义
		if (null == entityInfo1) {
			throw new ServiceException("crud.error.entity.definition",entityName);
		}
		List<Object> params= new ArrayList<>() ;  
		String sql = crudSqlGenerateUtils.buildInsertSql(entityInfo1.getTableName(), portalMultiEntityBean.getMap(), entityInfo1.getAttrs(),entityInfo1.getExtAttrs(), false,params);
		id = jdbcDao.insertAndGetKey(sql,params);
		AttachmentFormBean attachments = new AttachmentFormBean();
		if (portalMultiEntityBean.getMap().get("attachments") != null) {
			net.sf.json.JSONArray jry = net.sf.json.JSONArray.fromObject(portalMultiEntityBean.getMap().get("attachments"));
			List<PortalAttachmentForm> list1 = net.sf.json.JSONArray.toList(jry, PortalAttachmentForm.class);
			attachments.setAttachments(list1);
			portalAttachmentService.saveAttachmentForm(portalMultiEntityBean.getMap().get("generateFormId").toString(), attachments!=null?attachments.getAttachments():null);
		}
			
		portalMultiEntityBean = portalMultiEntityBean.getIsRelation();
		entityInfo1 = entityInfoQueryService.queryEntityInfo(portalMultiEntityBean.getEntityKey());
		// 获取实体定义
		if (null == entityInfo1) {
			throw new ServiceException("crud.error.entity.definition",entityName);
		}
		params= new ArrayList<>() ;  
		List<EntityFieldInfoBean> fileds = entityInfo1.getAttrs() ;
		for (EntityFieldInfoBean entityFieldInfoBean : fileds) {
			if(entityName.equals(entityFieldInfoBean.getField().getReferEntity())){
				portalMultiEntityBean.getMap().put(entityFieldInfoBean.getField().getFieldName(), id);
			}
		}
		
		sql = crudSqlGenerateUtils.buildInsertSql(entityInfo1.getTableName(), portalMultiEntityBean.getMap(), entityInfo1.getAttrs(),entityInfo1.getExtAttrs(), true,params);
		jdbcDao.executeBySQL(sql,params);
		attachments = new AttachmentFormBean();
		if (portalMultiEntityBean.getMap().get("attachments") != null) {
			net.sf.json.JSONArray jry = net.sf.json.JSONArray.fromObject(portalMultiEntityBean.getMap().get("attachments"));
			List<PortalAttachmentForm> list1 = net.sf.json.JSONArray.toList(jry, PortalAttachmentForm.class);
			attachments.setAttachments(list1);
			portalAttachmentService.saveAttachmentForm(portalMultiEntityBean.getMap().get("generateFormId").toString(), attachments!=null?attachments.getAttachments():null);
		}
	}

	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param list
	    * @param attachments
	    * @return
	    * @see com.efast.cafe.commponent.crud.service.ICrudV2Service#crudInsert(java.util.List, java.util.List)
	    */
	    
	@Override
	public List<Integer> crudInsert(Map<String, Object> t1,Map<String, Object> t2) {
		List<Integer> ids = new ArrayList<>();
		
		String tableName1 = t1.get("dataService_crud_entityName").toString();
		EntityInfoBean entityInfo1 = entityInfoQueryService.queryEntityInfo(tableName1);
		if(entityInfo1==null){
			throw new ServiceException("Entity 未定义");
		}
		t1.remove("dataService_crud_entityName");
		if(t1.get("dataService_crud_attachmentList")!=null){
			AttachmentFormBean attachments = (AttachmentFormBean)t1.get("dataService_crud_attachmentList");
			t1.remove("dataService_crud_attachmentList");
			Integer resId = crudInsert(tableName1,t1,attachments);
			ids.add(resId);
		}else{
			Integer resId = crudInsert(tableName1,t1,null);
			ids.add(resId);
		}
		
		String tableName2 = t2.get("dataService_crud_entityName").toString();
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(tableName2);
		if(entityInfo==null){
			throw new ServiceException("Entity 未定义");
		}
		entityInfo.getAttrs().forEach(f->{
			if(f.getField()!=null){
				if(f.getField().getReferEntity()!=null && f.getField().getReferEntity().equals(tableName1)){
					if(f.getField().getReferPro()!=null){
						t2.put(f.getField().getFieldName(), ids.get(0));
					}
				}
			}
		});
		t2.remove("dataService_crud_entityName");
		if(t2.get("dataService_crud_attachmentList")!=null){
			AttachmentFormBean attachments = (AttachmentFormBean)t2.get("dataService_crud_attachmentList");
			t2.remove("dataService_crud_attachmentList");
			Integer resId = crudInsert(tableName2,t2,attachments);
			ids.add(resId);
		}else{
			Integer resId = crudInsert(tableName2,t2,null);
			ids.add(resId);
		}
		return ids;
	}

	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param list
	    * @param attachments
	    * @see com.efast.cafe.commponent.crud.service.ICrudV2Service#crudUpdate(java.util.List, java.util.List)
	    */
	    
	@Override
	public void crudUpdate(List<Map<String, Object>> list) {
		for(Map<String, Object> map : list){
			String tableName = map.get("dataService_crud_entityName").toString();
			EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(tableName);
			if(entityInfo==null){
				throw new ServiceException("Entity 未定义");
			}
			map.remove("dataService_crud_entityName");
			if(map.get("dataService_crud_attachmentList")!=null){
				AttachmentFormBean attachments = (AttachmentFormBean)map.get("dataService_crud_attachmentList");
				map.remove("dataService_crud_attachmentList");
				crudUpdate(tableName,map,attachments);
			}else{
				crudUpdate(tableName,map,null);
			}
		}
	}
	
	@Override
	public void crudImport(String entityName, File uploadFile, Map<String, String> maps, Map<String, Object> maps2,List<Map<String, Object>> importConfig) {
		// TODO Auto-generated method stub
		try {
			StringBuffer str = new StringBuffer() ;
			XSSFWorkbook book = null;
			book = new XSSFWorkbook(new FileInputStream(uploadFile));
			XSSFSheet sheet = book.getSheetAt(0);
			List<Map<String, Object>> mapsList = new ArrayList<>() ;
			XSSFRow rowHeader = sheet.getRow(0);
			str.append(CrudSqlGenerateUtils.FIELD_IMPORT_SHEET+sheet.getSheetName());
			for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum
				// 获取最后一行的行标
				XSSFRow row = sheet.getRow(j);
				if (row != null) {
					Map<String, Object> map = new HashMap<>() ;
					for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum
						// 是获取最后一个不为空的列是第几个
						if (row.getCell(k) != null) { // getCell 获取单元格数据
							System.out.print(row.getCell(k) + "\t");
						} else {
							System.out.print("\t");
						}
						Cell cell = row.getCell(k);
						// 以下是判断数据的类型
						Object cellValue = null ;
						if(cell!=null){
							switch (cell.getCellType()){
							case HSSFCell.CELL_TYPE_NUMERIC: // 数字
								
								if (0 == cell.getCellType()) {//判断单元格的类型是否则NUMERIC类型
									if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判断是否为日期类型
										Date date = cell.getDateCellValue();
										DateFormat formater = new SimpleDateFormat(
												"yyyy-MM-dd HH:mm");
										cellValue = formater.format(date);
									}else{
										cellValue = (cell.getNumericCellValue()+"").endsWith(".0")?(cell.getNumericCellValue()+"").replaceAll(".0", ""): (cell.getNumericCellValue()+"");
									}
								}
								break;
							case HSSFCell.CELL_TYPE_STRING: // 字符串
								cellValue = cell.getStringCellValue();
								break;
							case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
								cellValue = cell.getBooleanCellValue() + "";
								break;
							case HSSFCell.CELL_TYPE_FORMULA: // 公式
								cellValue = cell.getCellFormula() + "";
								break;
							case HSSFCell.CELL_TYPE_BLANK: // 空值
								cellValue = "";
								break;
							case HSSFCell.CELL_TYPE_ERROR: // 故障
								cellValue = "非法字符";
								break;
							default:
								cellValue = "未知类型";
								break;						
							}
							//通用校验数据格式及验证 
							cellValue = doValidation(cellValue,(EntityFieldInfoBean)maps2.get(rowHeader.getCell(k).toString()),j,k,str);
							map.put(((String)maps.get(rowHeader.getCell(k).toString())), cellValue);
						}else{
							map.put(((String)maps.get(rowHeader.getCell(k).toString())), cellValue);
						}
					}
					mapsList.add(map) ;
				}
			}
			
			Map<String, Object> maps3 = new HashMap<>() ;
			for (Map<String, Object> map : importConfig) {
				maps3.put((String)map.get("fieldName"), map);
			}
			
			Map<String, String> selectMap = new HashMap<>() ; 
			List<PortalBaseLov> portalBaseLovs = portalBaseLovService.api_queryListByParamKey2(importConfig);
			for (Map<String, Object> map : importConfig) {
				for (PortalBaseLov portalBaseLov : portalBaseLovs) {
					if(portalBaseLov.getParam_key().equals((String)map.get("paramKey1"))){
						selectMap.put(portalBaseLov.getOption_desc(), portalBaseLov.getOption_key());
					}
				}
			}
			for (Map<String, Object> map : mapsList) {
				if(!maps3.isEmpty()){
					for(Map.Entry<String, Object> entry : maps3.entrySet()){
						if(entry!=null){
							Map<String, Object> importConfigData = (Map) entry.getValue() ;
							if("number".equals(importConfigData.get("valueType"))){
								map.put((String)importConfigData.get("fieldName"), jdbcDao.executeProcGetCode((String)importConfigData.get("paramKey1"), (String)importConfigData.get("paramKey2")));
							}else{
								if(map.containsKey(entry.getKey())){
									map.put(entry.getKey(), selectMap.get(map.get(entry.getKey())));
								}
							}
						}
					}
				}
				this.crudInsert(entityName, map, null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			
			throw new ServiceException(e.getMessage());
		}
	}
	
	
	@Override
	public void crudImportMulti(EntityInfoBean entityName,XSSFSheet sheet, Map<String, String> maps, Map<String, Object> maps2,List<Map<String, Object>> importConfig) {
		// TODO Auto-generated method stub
		try {
			StringBuffer stringBuffer = new StringBuffer() ;
			List<Map<String, Object>> mapsList = new ArrayList<>() ;
			XSSFRow rowHeader = sheet.getRow(0);
			for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum
				// 获取最后一行的行标
				XSSFRow row = sheet.getRow(j);
				if (row != null) {
					Map<String, Object> map = new HashMap<>() ;
					for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum
						// 是获取最后一个不为空的列是第几个
						if (row.getCell(k) != null) { // getCell 获取单元格数据
							System.out.print(row.getCell(k) + "\t");
						} else {
							System.out.print("\t");
						}
						Cell cell = row.getCell(k);
						// 以下是判断数据的类型
						Object cellValue = null ;
						if(cell!=null){
							switch (cell.getCellType()){
							case HSSFCell.CELL_TYPE_NUMERIC: // 数字
								
								if (0 == cell.getCellType()) {//判断单元格的类型是否则NUMERIC类型
									if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判断是否为日期类型
										Date date = cell.getDateCellValue();
										DateFormat formater = new SimpleDateFormat(
												"yyyy-MM-dd HH:mm");
										cellValue = formater.format(date);
									}else{
										cellValue = (cell.getNumericCellValue()+"").endsWith(".0")?(cell.getNumericCellValue()+"").replaceAll(".0", ""): (cell.getNumericCellValue()+"");
									}
								}
								break;
							case HSSFCell.CELL_TYPE_STRING: // 字符串
								cellValue = cell.getStringCellValue();
								break;
							case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
								cellValue = cell.getBooleanCellValue() + "";
								break;
							case HSSFCell.CELL_TYPE_FORMULA: // 公式
								cellValue = cell.getCellFormula() + "";
								break;
							case HSSFCell.CELL_TYPE_BLANK: // 空值
								cellValue = "";
								break;
							case HSSFCell.CELL_TYPE_ERROR: // 故障
								cellValue = "非法字符";
								break;
							default:
								cellValue = "未知类型";
								break;						
							}
							//通用校验数据格式及验证 
							cellValue = doValidation(cellValue,(EntityFieldInfoBean)maps2.get(rowHeader.getCell(k).toString()),j,k,stringBuffer);
							map.put(((String)maps.get(rowHeader.getCell(k).toString())), cellValue);
						}else{
							cellValue = doValidation(cellValue,(EntityFieldInfoBean)maps2.get(rowHeader.getCell(k).toString()),j,k,stringBuffer);
							map.put(((String)maps.get(rowHeader.getCell(k).toString())), cellValue);
						}
					}
					mapsList.add(map) ;
				}
			}
			
			if(!StringUtil.isNullOrBlank(stringBuffer.toString())){
				throw new ServiceException(stringBuffer.toString());
			}
			Map<String, Object> maps3 = new HashMap<>() ;
			for (Map<String, Object> map : importConfig) {
				maps3.put((String)map.get("fieldName"), map);
			}
			
			Map<String, String> selectMap = new HashMap<>() ; 
			List<PortalBaseLov> portalBaseLovs = portalBaseLovService.api_queryListByParamKey2(importConfig);
			for (Map<String, Object> map : importConfig) {
				for (PortalBaseLov portalBaseLov : portalBaseLovs) {
					if(portalBaseLov.getParam_key().equals((String)map.get("paramKey1"))){
						selectMap.put(portalBaseLov.getOption_desc(), portalBaseLov.getOption_key());
					}
				}
			}
			for (Map<String, Object> map : mapsList) {
				if(!maps3.isEmpty()){
					for(Map.Entry<String, Object> entry : maps3.entrySet()){
						if(entry!=null){
							Map<String, Object> importConfigData = (Map) entry.getValue() ;
							if("number".equals(importConfigData.get("valueType"))){
								map.put((String)importConfigData.get("fieldName"), jdbcDao.executeProcGetCode((String)importConfigData.get("paramKey1"), (String)importConfigData.get("paramKey2")));
							}else{
								if(map.containsKey(entry.getKey())){
									map.put(entry.getKey(), selectMap.get(map.get(entry.getKey())));
								}
							}
						}
					}
				}
				this.crudInsert(entityName.getEntityName(), map, null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			
			throw new ServiceException(e.getMessage());
		}
	}
	

	private Object doValidation(Object paramValue, EntityFieldInfoBean info,int rowNum,int columnNum,StringBuffer str ) {
		EntityFieldDetailBean detail = info.getField();
		// 字段类型.1:string,2:int,3:double,4:date 5:boolean
		StringBuffer stringBuffer = new StringBuffer() ;
		stringBuffer.append(CrudSqlGenerateUtils.FIELD_IMPORT_DI+rowNum + CrudSqlGenerateUtils.FIELD_IMPORT_ROW+ CrudSqlGenerateUtils.FIELD_IMPORT_DI+columnNum + CrudSqlGenerateUtils.FIELD_IMPORT_COLUMN +";\n");
		if (detail.getFieldType().intValue() == 1) {
			// 非空校验
			if (detail.getRequired() == 1 && (paramValue == null || StringUtil.isNullOrBlank(paramValue.toString()))) {
				throw new ServiceException(stringBuffer.toString()+ CrudSqlGenerateUtils.FIELD_CAN_NOT_BE_EMPTY,detail.getFieldName());
			}
			if (StringUtil.isNotBlank(info.getValidation())) {
				JSONObject jo = JSONObject.fromObject(info.getValidation());
				StringValidationBean validationBean = (StringValidationBean) JSONObject.toBean(jo, StringValidationBean.class);
				if (validationBean.getMinLength() != null) {
					if (paramValue != null && paramValue.toString().length() < validationBean.getMinLength().intValue()) {
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) + CrudSqlGenerateUtils.FIELD_MIN_LENGTH_ERROR+";\n");// 最小长度校验失败
					}
				}
				if (validationBean.getMaxLength() != null) {
					if (paramValue != null && paramValue.toString().length() > validationBean.getMaxLength().intValue()) {
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_MAX_LENGTH_ERROR+";\n");// 最大长度校验失败
					}
				}
				if (validationBean.getCheckType() != null) {
					for (String checkType : validationBean.getCheckType()) {
						if (paramValue == null || !crudSqlGenerateUtils.checkString(checkType, ObjectUtils.toString(paramValue))) {
							str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) + CrudSqlGenerateUtils.FIELD_CHECK_TYPE_ERROR+";\n");
						}
					}
				}
				if (StringUtil.isNotBlank(validationBean.getRegx())) {
				}
			}
		}

		if (detail.getFieldType().intValue() == 2) {// 校验int类型数据
			// 非空校验
			if (detail.getRequired() == 1 && paramValue == null) {
				str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) + CrudSqlGenerateUtils.FIELD_CAN_NOT_BE_EMPTY+";\n");
			}
			if (StringUtil.isNotBlank(info.getValidation())) {
				JSONObject jo = JSONObject.fromObject(info.getValidation());
				IntValidationBean validationBean = (IntValidationBean) JSONObject.toBean(jo,
				    IntValidationBean.class);
				if (validationBean.getMin() != null && paramValue != null) {
					Integer intParamValue = Integer.parseInt(paramValue.toString());
					if (intParamValue.intValue() < validationBean.getMin().intValue()) {
						// 最小值校验不通过
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_MINVALUE_ERROR+";\n");
					}
				}
				if (validationBean.getMax() != null && paramValue != null) {
					Integer intParamValue = Integer.parseInt(paramValue.toString());
					if (intParamValue.intValue() > validationBean.getMax().intValue()) {
						// 最大值校验不通过
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_MAXVALUE_ERROR+";\n");
					}
				}
			}
		}

		if (detail.getFieldType().intValue() == 3) {
			// 非空校验
			if (detail.getRequired() == 1 && paramValue == null) {
				str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_CAN_NOT_BE_EMPTY+";\n");
			}
			if (StringUtil.isNotBlank(info.getValidation())) {
				JSONObject jo = JSONObject.fromObject(info.getValidation());
				DoubleValidationBean validationBean = (DoubleValidationBean) JSONObject.toBean(jo,
				    DoubleValidationBean.class);
				if (validationBean.getLength() != null && paramValue != null) {
					if (paramValue.toString().length() > validationBean.getLength().intValue()) {
						// double类型length总长度校验不通过
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_CHECK_TYPE_ERROR+";\n");
					}
				}
				if (validationBean.getPrecision() != null && paramValue != null) {
					if (paramValue.toString().indexOf(".") != -1
					    && paramValue.toString()
					        .substring(paramValue.toString().indexOf(".") + 1,
					            paramValue.toString().length())
					        .length() > validationBean.getPrecision().intValue()) {
						// double类型precision 小数点后几位校验不通过
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_CHECK_TYPE_ERROR+";\n");
					}
				}
				if (validationBean.getMin() != null && paramValue != null) {
					Double doubleValue = Double.parseDouble(paramValue.toString());
					if (doubleValue.doubleValue() < validationBean.getMin().doubleValue()) {
						// double类型 min 最小值校验不通过
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_MINVALUE_ERROR+";\n");
					}
				}
				if (validationBean.getMax() != null && paramValue != null) {
					Double doubleValue = Double.parseDouble(paramValue.toString());
					if (doubleValue.doubleValue() > validationBean.getMax().doubleValue()) {
						// double类型 max 最小值校验不通过
						str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_MAXVALUE_ERROR+";\n");
					}
				}
			}
		}

		if (detail.getFieldType().intValue() == 4) {
			// 非空校验
			if (detail.getRequired() == 1 && paramValue == null) {
				str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_CAN_NOT_BE_EMPTY+";\n");
			}
			if (StringUtil.isNotBlank(info.getValidation())) {
				JSONObject jo = JSONObject.fromObject(info.getValidation());
				DateValidationBean validationBean = (DateValidationBean) JSONObject.toBean(jo,
				    DateValidationBean.class);
				if (StringUtil.isNotBlank(validationBean.getFormat()) && paramValue != null) {
					paramValue= paramValue != null ? DateUtils.format(DateUtils.parse(paramValue.toString(),validationBean.getFormat()), validationBean.getFormat()) : null;
				}
			} else {
				if (paramValue != null) {
					paramValue=  DateUtils.format(DateUtils.parse(paramValue.toString(),DateUtils.FORMAT_DATE_YYYY_MM_DD), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS) ;
				}
			}
		}

		if (detail.getFieldType().intValue() == 5) {
			// 非空校验
			if (detail.getRequired() == 1 && paramValue == null) {
				str.append(stringBuffer.toString()+LanguageUtil.getValueByJsonLocale(detail.getI18nName()) +CrudSqlGenerateUtils.FIELD_CAN_NOT_BE_EMPTY+";\n");
			}
//			sqlBuilder.append(columnName).append(" = ? , ");
//			params.add(paramValue != null ? Integer.parseInt(paramValue.toString()) : null);
		}
		// file 不处理
		if (detail.getFieldType().intValue() == 6) {

		}

		// json or entity
		if (detail.getFieldType().intValue() == 7 || detail.getFieldType().intValue() == 8) {
			paramValue = paramValue != null ? paramValue.toString() : null;
		}
		
		//time
		if (detail.getFieldType().intValue() == 9) {
			paramValue = paramValue != null ? paramValue.toString() : null;
		}
		return paramValue;
	}
}
